package edu.kit.csl.cratyli.control;

import java.io.IOException;

import edu.kit.csl.cratyli.datatypes.BadParameterValueException;
import edu.kit.csl.cratyli.datatypes.Dictionary;
import edu.kit.csl.cratyli.datatypes.TextCorpus;
import edu.kit.csl.cratyli.ui.Logger;

/**
 * This combination order strategy starts with the primary cratylus run, and
 * the successively adds the secondary runs in a sequential order.
 */
public class IncrementalOrderStrategy extends CombinationOrderStrategy {

	/* (non-Javadoc)
	 * @see CombinationOrderStrategy#CombinationOrderStrategy() 
	 */
	public IncrementalOrderStrategy() throws BadParameterValueException {
		super();
	}

	/**
	 * Combine the primary and the first secondary run first, and then 
	 * successively add the remaining secondary runs to the resulting text
	 * corpus and dictionary.
	 */
	@Override
	public void startCombining() {
		Logger log = Logger.getSingleton();
		try {
			Dictionary dict = Dictionary.loadFromFile(primPath + ".dict");
			TextCorpus corpus = TextCorpus.loadFromFiles(
					primPath + ".plain.trgt", primPath + ".ids");
			corpus.removeDuplicates();
			dict.collectWeights(corpus);
			corpus.filterByWeight(dict, minWeight);
			int i = 1;
			for (String path : secPaths) {
				log.notice("Load secondary run from " + path);
				Dictionary secDict = Dictionary.loadFromFile(path + ".dict");
				TextCorpus secCorpus = TextCorpus.loadFromFiles(
						path + ".plain.trgt", path + ".ids");
				secCorpus.removeDuplicates();
				secDict.collectWeights(secCorpus);
				secCorpus.filterByWeight(secDict, minWeight);
				dict.add(secDict);
				log.notice("Combine text corpora..");
				corpus = combiner.combine(dict, corpus, secCorpus);
				dict = reducer.reduce(dict, corpus);
				corpus.removeDuplicates();
				log.notice("Dictionary size is now " + dict.size());
				writeToFileSystem(Integer.toString(i + 1), i, dict, corpus);
				i++;
			}
		} catch(IOException e) {
			log.fatalError("Could not load one of the corpora: "
					+ e.getMessage());
		}	
	}
}
